package components

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/gaoyue1989/sshexec"
	"library/common"
	"models"
	"time"
)



type ScriptBaseComponents struct {
	name    string
	script   *models.GjScriptTask
}

func (c *ScriptBaseComponents) SetScriptTask(task *models.GjScriptTask) {
	c.script = task
}


/**
* 执行远端目标机命令
 */
func (c *ScriptBaseComponents) RunRemoteCommand(command string,  hosts []string) ([]sshexec.ExecResult, error) {
	timeout := c.script.Timeout
	TimeOut := 0
	if timeout != 0{
		TimeOut = timeout
	}else {
		TimeOut = SSHREMOTETIMEOUT
	}
	id := c.SaveRecord(command)
	start := time.Now()
	createdAt := int(start.Unix())
	sshExecAgent := sshexec.SSHExecAgent{}
	sshExecAgent.Worker = SSHWorker
	sshExecAgent.TimeOut = time.Duration(TimeOut) * time.Second
	s, err := sshExecAgent.SshHostByKey(hosts, c.script.ReleaseUser, command)
	//获取执行时间
	duration := common.GetInt(time.Now().Sub(start).Seconds())
	status := 1
	if err != nil {
		status = 0
		//超时了kill掉任务
		err1 := KillProcess(command,hosts)
		if err1 != nil {
			beego.Info(err.Error())
		}
	}

	c.SaveRecordRes(id, duration, createdAt, status, s)
	return s, err
}

func (c *ScriptBaseComponents) SaveRecord(command string) int {
	re := models.GjScriptRecord{}
	re.Command = command
	if c.script == nil || c.script.Id == 0 {
		re.TaskId = -99
	} else {
		re.TaskId = c.script.Id
	}
	re.Status = 1
	id, err := models.AddGjScriptRecord(&re)
	if err != nil {
		beego.Error(err)
	}
	beego.Info("id:", id)
	return int(id)
}

func (c *ScriptBaseComponents) SaveRecordRes(id int, duration int, createdAt int, status int, value interface{}) {
	beego.Info(value)
	if duration < 0 {
		duration = 0
	}
	beego.Info("id1:", id)
	re, err := models.GetGjScriptRecordById(id)
	if err != nil {
		beego.Error(err)
		return
	}
	re.IsFinal = 1
	re.Duration = duration
	sResult, _ := json.Marshal(value)
	re.CreatedAt = createdAt
	re.Memo = string(sResult)
	re.Status = int16(status)
	err = models.UpdateGjScriptRecordById(re)
	if err != nil {
		beego.Error(err)
	}
}

